package com.nmgydy.util;

import java.security.MessageDigest;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;

public class Secret {
	
	/** MD5加密 **/
	public final static String encodeMD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {

			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

	/** BASE64编码 */
	public static String encoderBASE64(String s) {
		if (s == null) {
			return null;
		}
		return new String(Base64.encodeBase64(s.getBytes()));
	}


	/** BASE64解码 */
	public static String decoderBASE64(String s) {
		String rtn = null;
		if (s != null && !s.isEmpty()) {
			try {
				return new String(Base64.decodeBase64(s.getBytes()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return rtn;
	}

	/** 获取32位GUID */
	public static String getUUID() {
		return java.util.UUID.randomUUID().toString().replace("-", "");
	}

	/** 获取客户端IP地址 */
	public static String getIPAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	public static String encodeDES(String value, String key) throws Exception {
		EncryptionDecryption des = new EncryptionDecryption(key);
		return des.encrypt(value);
	}

	public static String decodeDES(String value, String key) throws Exception {
		EncryptionDecryption des = new EncryptionDecryption(key);
		return des.decrypt(value);
	}

}
